/**
 *
 * Copyright 2016-present scrm
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
import React from 'react';
import {
  StyleSheet,
  BackHandler,
  Dimensions,
  Text,
  Image,
  TouchableOpacity,
  TouchableWithoutFeedback,
  View,
  Modal,
  NativeModules,
  Platform
} from 'react-native';

import * as WeChat from 'react-native-wechat';
import Icon from 'react-native-vector-icons/Ionicons';
import ToastUtil from '../../utils/ToastUtil';
import { getEncryptedToken, getEncryptedTokenFromStore, refactTokenToAuthData, getSignatureDataFromStore } from '../../utils/TokenUtil';
import LoadingView from '../../components/LoadingView';
import { formatStringWithHtml } from '../../utils/FormatUtil';
import store from 'react-native-simple-store';
import Webview from '../../components/webview/webview';

let canGoBack = false;
const shareIconWechat = require('../../img/share_icon_wechat.png');
const shareIconMoments = require('../../img/share_icon_moments.png');
const AESData = require('../../data/AE01.json');

const ReactAES = NativeModules.ReactAES;

class SCRMWebViewPage extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isShareModal: false
    };

    this.messageList = []
    this.isAuth = false;
    this.handleMessage = this.handleMessage.bind(this)
    this.onNavButtonPress = this.onNavButtonPress.bind(this)
  }

  componentDidMount() {
    console.log('SCRMWebViewPage')
    this.setNavPrams();
    BackHandler.addEventListener('hardwareBackPress', this.goBack);
    // const { teamActions } = this.props;
    // store.get('token')
    //   .then((token) => {
    //     teamActions.requestTeamList(token, false, true);
    //   })
  }

  componentWillUnmount() {
    BackHandler.removeEventListener('hardwareBackPress', this.goBack);
  }

  setNavPrams (params) {
    this.props.navigation.setParams(Object.assign({}, 
      params || {},
      { handleRefresh: this.onNavButtonPress },
    ))
  }

  onNavButtonPress () {
    this.webview.reload();
    // if (Platform.OS === 'ios') {
    //   this.webview.reload();
    // } else {
    //   this.webview.reload();
    // }
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.auth && nextProps.auth.auth === true) {
      const {key, iv} = AESData;
      let message = nextProps.auth.message;

      if (message.api === 'config') {
        this.isAuth = true
        if (this.messageList[message.id]) {
          store.get('token')
          .then(token => this.responseWithToken(token, message))
        }
      } else if (message.api === 'getToken') {
        const chiper = nextProps.auth.encryptedToken;
        getEncryptedToken(chiper, key, iv)
          .then(token => {
            store.save('token', token)
            this.responseWithToken(token, message)
          })
      }
    }
  }

  responseWithToken(token, message) {
    message.response = {token: token}
    // this.webview.postMessage(JSON.stringify(message))
    this.postMessage(JSON.stringify(message))
    delete this.messageList[message.id]
  }

  onActionSelected = () => {
    this.setState({
      isShareModal: true
    });
  };

  handleMessage (e) {
    try {
      const data  = Platform.OS === 'ios' ? e.body : e.nativeEvent.data;
      if (/^\{.*\}$/.test(data)) {
        // const data = e.nativeEvent.data;
        const message = JSON.parse(data)
        if (message.api === 'config') {
          this.configAuth(message)
        } else {
          if (this.props.auth.auth === true) {
            if(message.api === 'getToken'){
              this.getToken(message);
            } else if(message.api === 'biz.navigation.navigate'){
              this.navigate(message);
            } else if(message.api === 'biz.msg.setCount'){
              this.setMsgCount(message);
            } else if(message.api === 'biz.navigation.setTitle'){
              this.changeThisTitle(message.params.title)
            } else if(message.api === 'biz.navigation.back'){
              requestAnimationFrame(() => this.props.navigation.goBack())
            } else {
              this.postMessage(data);
            }
          } else {
            this.postMessage(data);
          }
        }
      }
        
    } catch (e) {
      console.log(e)
    }
  }

  postMessage (data) {
    // console.log('postMessage', data)
    if (Platform.OS  === 'ios') {
      this.webview.evaluateJavaScript('receivedMessageFromReactNative(' + data + ')');
    } else {
      this.webview.postMessage(data);
    }
    
  }

  isJsonStr(str) {
    return (/^\{.*\}$/.test(str));
  };


  setMsgCount (message) {
    try {
      const { msgActions } = this.props;
      // console.log('msgContainer', JSON.stringify(message))
      msgActions.updateMsgCount(message.params.count )
      this.props.navigation.setParams({ count: message.params.count })
    } catch(e) {
      console.log(e,' e')
    }
  }

  getJson(str) {
    const searchJsonArr = /\{.*\}/.exec(str)
    return searchJsonArr.length > 0 ? JSON.parse(searchJsonArr[0]) : {}
  }

  changeThisTitle = (titleText) => {
    this.setNavPrams({ title: titleText });
  }

 
  configAuth (message) {
    const { authActions }  = this.props;
    const {signature, nonceStr, timeStamp } = message.params;
    try {
      this.auth = false;
      authActions.requestVerifySignature(signature, nonceStr, timeStamp, message)
      this.messageList[message.id] = message;
    } catch(e) {
      console.log(e)
    }
  }

  androidViewStyle () {

  }

  getToken (message) {
    const { authActions }  = this.props;
    const {key, iv} = AESData;
    try {
      getSignatureDataFromStore('authData', key, iv)
        .then((signatureData) => {
          const {site_id, uim, suid, timeStamp, signature} = signatureData;
          authActions.requestToken(site_id, uim, suid, timeStamp, signature, message);
        })
      this.auth = false;
      this.messageList[message.id] = message;
    } catch(e) {
    }
  };

  navigate (message) {
    try {
      const { navigate } = this.props.navigation;
      let { params } = this.props.navigation.state; 
      let extra = {}

      if (params.beforeNavigate) {
        const freshPrams = params.beforeNavigate(params);
        const histories = params.histories || [];
        histories.push({
          backFromScreen: freshPrams.backFromScreen,
          previousState: { article: params.article }
        })
        extra = { histories: histories };
      }
      
      const target = Object.assign({
        article: {
          url: message.params.url,
          title: (message.params.params || {}).title,
          data: message.params.params
        }
      }, extra);

      if (params && params.title) {
        this.changeThisTitle(params.title)
      }

      requestAnimationFrame(() => navigate('scrm', target));
      // this.responseWithToken()
    } catch(e) {
    }
  };

  onNavigationStateChange = (navState) => {
    canGoBack = navState.canGoBack;
  };

  goBack = () => {
    if (this.state.isShareModal) {
      this.setState({
        isShareModal: false
      });
      return true;
    } else if (canGoBack) {
      this.webview.goBack();
      return true;
    }
    return false;
  };

  renderLoading = () => <LoadingView />;

  renderSpinner = () => {
    let { params } = this.props.navigation.state;
    if (!params || !params.article) {
      params = this.props.params
    }

    return (
      <TouchableWithoutFeedback
        onPress={() => {
          this.setState({
            isShareModal: false
          });
        }}
      >
        <View key="spinner" style={styles.spinner}>
          <View style={styles.spinnerContent}>
            <Text
              style={[styles.spinnerTitle, { fontSize: 20, color: 'black' }]}
            >
              分享到
            </Text>
            <View style={styles.shareParent}>
              <TouchableOpacity
                style={styles.base}
                onPress={() => {
                  WeChat.isWXAppInstalled().then((isInstalled) => {
                    if (isInstalled) {
                      WeChat.shareToSession({
                        title: formatStringWithHtml(params.article.title),
                        description: '分享自：Scrm',
                        thumbImage: params.article.contentImg,
                        type: 'news',
                        webpageUrl: params.article.url
                      }).catch((error) => {
                        ToastUtil.showShort(error.message, true);
                      });
                    } else {
                      ToastUtil.showShort('没有安装微信软件，请您安装微信之后再试', true);
                    }
                  });
                }}
              >
                <View style={styles.shareContent}>
                  <Image style={styles.shareIcon} source={shareIconWechat} />
                  <Text style={styles.spinnerTitle}>微信</Text>
                </View>
              </TouchableOpacity>
              <TouchableOpacity
                style={styles.base}
                onPress={() => {
                  WeChat.isWXAppInstalled().then((isInstalled) => {
                    if (isInstalled) {
                      WeChat.shareToTimeline({
                        title: formatStringWithHtml(`[@Scrm]${params.article.title}`),
                        thumbImage: params.article.contentImg,
                        type: 'news',
                        webpageUrl: params.article.url
                      }).catch((error) => {
                        ToastUtil.showShort(error.message, true);
                      });
                    } else {
                      ToastUtil.showShort('没有安装微信软件，请您安装微信之后再试', true);
                    }
                  });
                }}
              >
                <View style={styles.shareContent}>
                  <Image style={styles.shareIcon} source={shareIconMoments} />
                  <Text style={styles.spinnerTitle}>朋友圈</Text>
                </View>
              </TouchableOpacity>
            </View>
          </View>
        </View>
      </TouchableWithoutFeedback>
    );
  };

  render() {
    let { params } = this.props.navigation.state;

    if (!params || !params.article) {
      params = this.props
    }

    return (
      <View style={styles.container}>
        <Modal
          animationType="fade"
          visible={this.state.isShareModal}
          transparent
          onRequestClose={() => {
            this.setState({
              isShareModal: false
            });
          }}
        >
          {this.renderSpinner()}
        </Modal>
        { Platform.OS === 'ios' &&
          <Webview
            ref={(ref) => {
              this.webview = ref;
            }}
            bounces={false}
            style={styles.base}
            source={{ uri: params.article.url }}
            javaScriptEnabled
            domStorageEnabled
            startInLoadingState
            scalesPageToFit
            decelerationRate="normal"
            onMessage={this.handleMessage}
            onShouldStartLoadWithRequest={(target) => {
              const shouldStartLoad = true;
              return shouldStartLoad;
            }}
            onNavigationStateChange={this.onNavigationStateChange}
            renderLoading={this.renderLoading}
          />
          ||
          <Webview
            ref={(ref) => {
              this.webview = ref;
            }}
            bounces={false}
            style={styles.base}
            source={{ uri: params.article.url }}
            javaScriptEnabled
            domStorageEnabled
            startInLoadingState
            scalesPageToFit
            decelerationRate="normal"
            onMessage={this.handleMessage}
            onShouldStartLoadWithRequest={(target) => {
              const shouldStartLoad = true;
              return shouldStartLoad;
            }}
            onNavigationStateChange={this.onNavigationStateChange}
            renderLoading={this.renderLoading}
          />
         }
      </View>
    );
  }
}

const styles = StyleSheet.create({
  base: {
  },
  container: {
    flex: 1,
  },
  spinner: {
    flex: 1,
    flexDirection: 'column',
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: 'rgba(0, 0, 0, 0.65)'
  },
  spinnerContent: {
    justifyContent: 'center',
    width: Dimensions.get('window').width * (7 / 10),
    height: Dimensions.get('window').width * (7 / 10) * 0.68,
    backgroundColor: '#fcfcfc',
    padding: 20,
    borderRadius: 5
  },
  spinnerTitle: {
    fontSize: 18,
    color: '#313131',
    textAlign: 'center',
    marginTop: 5
  },
  shareParent: {
    flexDirection: 'row',
    marginTop: 20
  },
  shareContent: {
    flexDirection: 'column',
    justifyContent: 'center',
    alignItems: 'center'
  },
  shareIcon: {
    width: 40,
    height: 40
  }
});

export default SCRMWebViewPage;
